package com.yanfan.product.controller;


import cn.hutool.core.util.StrUtil;
import com.yanfan.common.config.RuoYiConfig;
import com.yanfan.common.core.controller.BaseController;
import com.yanfan.common.core.domain.AjaxResult;
import com.yanfan.common.exception.file.FileNameLengthLimitExceededException;
import com.yanfan.common.utils.file.FileUploadUtils;
import com.yanfan.common.utils.file.MimeTypeUtils;
import com.yanfan.energy.domain.BaseOrderEntity;
import com.yanfan.energy.domain.DispatchList;
import com.yanfan.energy.domain.DispatchListHead;
import com.yanfan.energy.domain.ProductionDict;
import com.yanfan.energy.service.DispatchListService;
import com.yanfan.energy.service.ExcelService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 工单表(DispatchList)表控制层
 *
 * @author makejava
 * @since 2023-01-11 13:47:59
 */
@RestController
@RequestMapping("/production/dispatchList")
public class DispatchListController extends BaseController {
    /**
     * 服务对象
     */
    @Resource
    private DispatchListService dispatchListService;

    @Autowired
    private ExcelService excelService;

    public static String getExtension(MultipartFile file) {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StrUtil.isEmpty(extension)) {
            extension = MimeTypeUtils.getExtension(file.getContentType());
        }
        return extension;
    }

    /**
     * 分页查询
     *
     * @param dispatchList 筛选条件
     * @return 查询结果
     */
    @PostMapping("/queryByPage")
    public AjaxResult queryByPage(@RequestBody DispatchList dispatchList) {
        PageHelper.startPage(dispatchList.getCurrPage(), dispatchList.getPageSize());
        PageInfo<DispatchList> pageInfo = new PageInfo<>(dispatchListService.queryByPage(dispatchList));
        return AjaxResult.success("查询成功", pageInfo);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/queryById/{id}")
    public AjaxResult queryById(@PathVariable("id") Long id) {
        return AjaxResult.success(this.dispatchListService.queryById(id));
    }

    @PostMapping("/taskStart")
    @ApiOperation("任务开始")
    public AjaxResult taskStart(@ApiParam(name = "id", value = "工单id") @RequestParam Long id) {
        return AjaxResult.success(dispatchListService.taskStart(id));
    }

    @PostMapping("/taskFinish")
    @ApiOperation("任务完成")
    public AjaxResult taskFinish(@RequestBody DispatchList dispatchList) {
        return AjaxResult.success(dispatchListService.taskFinish(dispatchList));
    }

    /**
     * 新增数据
     *
     * @param dispatchList 实体
     * @return 新增结果
     */
    @PostMapping("/add")
    public AjaxResult add(@RequestBody DispatchList dispatchList) {
        return AjaxResult.success(this.dispatchListService.insert(dispatchList));
    }

    /**
     * 编辑数据
     *
     * @param dispatchList 实体
     * @return 编辑结果
     */
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody DispatchList dispatchList) {
        return AjaxResult.success(this.dispatchListService.update(dispatchList));
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping("/deleteById/{id}")
    public AjaxResult deleteById(@PathVariable("id") Long id) {
        return AjaxResult.success(this.dispatchListService.deleteById(id));
    }

    /**
     * 下载
     *
     * @return 查询结果
     */
    @PostMapping("/queryListReport")
    public void queryListReport(@RequestParam(required = false) String number, @RequestParam(required = false) String title, @RequestParam(required = false) Long state, @RequestParam(required = false) String conductor, HttpServletResponse response) throws IOException {
        DispatchList dispatchList = new DispatchList();
        dispatchList.setNumber(number);
        dispatchList.setTitle(title);
        dispatchList.setState(state);
        dispatchList.setConductorName(conductor);
        excelService.downloadList(DispatchListHead.class, dispatchListService.queryByPageReport(dispatchList), response, "工单列表");
    }

    /**
     * 文件上传
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            String filePath = RuoYiConfig.getProfile();
            // 文件名长度限制
            int fileNamelength = file.getOriginalFilename().length();
            if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
                throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
            }
            // 获取文件名和文件类型
            String fileName = file.getOriginalFilename();
            String extension = getExtension(file);
            //设置日期格式
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MMdd-HHmmss");
            fileName = "/workOrder/" + getLoginUser()
                    .getUserId()
                    .toString() + "/" + df.format(new Date()) + "." + extension;
            //创建目录
            File desc = new File(filePath + File.separator + fileName);
            if (!desc.exists()) {
                if (!desc.getParentFile().exists()) {
                    desc.getParentFile().mkdirs();
                }
            }
            // 存储文件
            file.transferTo(desc);

            String url = "/profile" + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", url);
            ajax.put("url", url);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * @return 问题分类列表
     */
    @PostMapping("/questionType")
    public ResponseEntity<List<ProductionDict>> questionType() {
        return ResponseEntity.ok(this.dispatchListService.questionType());
    }

    /**
     * @return 订单查询
     */
    @PostMapping("/queryOddNumbers")
    public ResponseEntity<List<BaseOrderEntity>> queryOddNumbers(@RequestParam(required = true) Integer type) {
        return ResponseEntity.ok(this.dispatchListService.queryOddNumbers(type));
    }

    /**
     * @return 单号类型查询
     */
    @PostMapping("/queryOddTypes")
    public ResponseEntity<List<BaseOrderEntity>> queryOddTypes() {
        return ResponseEntity.ok(this.dispatchListService.queryOddTypes());
    }
}

